package app.qrcode.browser.hearttoheart.adapters

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import app.qrcode.browser.hearttoheart.R

/**
 * Created by DomenCai on 2022/3/29.
 */
class MsgAdapter : RecyclerView.Adapter<MsgAdapter.MsgViewHolder>() {

    private val msgList: MutableList<Msg> = mutableListOf()

    @SuppressLint("NotifyDataSetChanged")
    fun updateList(newList: ArrayList<Msg>) {
        msgList.clear()
        msgList.addAll(newList)
        notifyDataSetChanged()
    }

    inner class MsgViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val personName: TextView = view.findViewById(R.id.personName_TV)
        val personHead: ImageView = view.findViewById(R.id.person_head)
        val personSays: TextView = view.findViewById(R.id.person_says)
        val personMsgIMG: ImageView = view.findViewById(R.id.msg_img)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MsgViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_msg, parent, false)
        return MsgViewHolder(view)
    }

    override fun onBindViewHolder(holder: MsgViewHolder, position: Int) {
        val msg = msgList[position]
        holder.personName.text = msg.personName
        msg.personIMG?.let { holder.personHead.setImageResource(it) }
        holder.personSays.text = msg.personSays
        msg.personMsgIMG?.let { holder.personMsgIMG.setImageResource(it) }
    }

    override fun getItemCount(): Int = msgList.size
}